package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.thoughtworks.xstream.XStream;

import entities.ListaDePrecios;
import entities.MateriaPrimaAPedirVO;
import entities.OrdenCompraCCAcepVO;
import entities.Rodamiento;

public class XMLParser {
	private static XStream xs = null;

	private XMLParser() {
		xs = new XStream();
		
		/** Materia Prima **/
		xs.alias("lista", java.util.List.class);
		xs.alias("materiaPrimaAPedirVO", MateriaPrimaAPedirVO.class);
		xs.alias("Rodamiento", Rodamiento.class);
		
		/** Lista De Precios **/
		xs.alias("ListaDePrecios",ListaDePrecios.class);
		xs.omitField(Rodamiento.class, "listaMateriasPrima");
		
		/** OrdenCompraCCAcepVO **/
		xs.alias("OrdenCompraCCAcepVO",OrdenCompraCCAcepVO.class);
	}

	public static synchronized String parsear(Object o) {
		generateXmlAndSave(o);
		return xs.toXML(o);
	}

	public static synchronized Object parsearObjeto(File f)
			throws FileNotFoundException {
		return xs.fromXML(new FileInputStream(f));
	}

	public static synchronized Object parseObject(String f) {
		return xs.fromXML(f);
	}

	public static synchronized void parsearYguardarArchivo(Object o, File f)
			throws IOException {
		FileOutputStream outputStream = new FileOutputStream(f);
		Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
		writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
		xs.toXML(o, writer);
	}

	public static void generateXmlAndSave(Object xmlObject) {
		String path = "C://ArchivosXML//";
		path += xmlObject.getClass().getSimpleName() + "-"
				+ new SimpleDateFormat("yyyyMMdd-hhss").format(new Date())
				+ ".xml";
		try {
			parsearYguardarArchivo(xmlObject, new File(path));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
